<template>
  <div ref="split" class="split">
    <h3>WebSocket客户端</h3>
    <div class="messages">
      <div v-for="msg in messages" :key="msg.id" class="message">
        <strong>{{ msg.type }}:</strong> {{ msg.content }}
      </div>
    </div>
    <div class="input-area">
      <input v-model="message" placeholder="输入消息">
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script lang="ts" setup>
// import PluginWebSocketClient from "@/utils/websocketClient";
defineOptions({
  name: 'TestView'
});

import { ref, onMounted, onUnmounted } from 'vue';


const messages = ref<Array<{ id: number, type: string, content: string }>>([]);
const message = ref('');
let ws: WebSocket | null = null;
let messageId = 0;

// 连接WebSocket服务器
const connect = () => {
  // 注意：浏览器中使用ws://，生产环境可能需要wss://
  ws = new WebSocket('ws://localhost:3002');

  ws.onopen = () => {
    addMessage('系统', '连接成功');
  };

  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      addMessage(data.type, data.message);
    } catch (error: any) {
      addMessage('系统', `收到消息: ${event.data}`);
    }
  };

  ws.onclose = () => {
    addMessage('系统', '连接已关闭');
  };

  ws.onerror = (error) => {
    addMessage('错误', `连接错误: ${error}`);
  };
};

// 添加消息到列表
const addMessage = (type: string, content: string) => {
  messages.value.push({
    id: messageId++,
    type,
    content
  });
};

// 发送消息
const sendMessage = () => {

  // 插件（3001）
  const channel = new BroadcastChannel('platform-plugin-channel');
  channel.onmessage = (event) => {
    console.log('Received from Platform:', event.data);
    channel.postMessage({ type: 'plugin-reply', payload: 'Hello from Plugin!' });
  };

  // if (!ws || ws.readyState !== WebSocket.OPEN || !message.value) return;

  // ws.send(JSON.stringify({
  //   type: 'chat',
  //   content: message.value
  // }));

  // message.value = '';
};

onMounted(() => {
  connect();
});

onUnmounted(() => {
  if (ws) {
    ws.close();
  }
});




</script>
<style scoped lang="scss"></style>
